package com.example.dakotanews.utils;

import com.example.dakotanews.dto.utils.ApiResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class AuthenticationHandler {
    /**
     * @description 针对认证和授权可能出现的情况进行响应的方法
     * @description 1、游客访问私有接口 2、用户认证过期 3、携带非法的JWT
     * @param response 该方法接受一个响应
     * @param status HttpServletResponse的状态
     * @param responseCode APIResponse的状态（自定义的系统默认响应体）
     * @param message 响应信息
     * @param data 响应数据
     */
    public void authHandler(HttpServletResponse response, int status, int responseCode, String message, Object data) throws IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        response.setStatus(status);

        ApiResponse<Object> apiResponse = new ApiResponse<>(responseCode, message, data);
        String jsonResponse = new ObjectMapper().writeValueAsString(apiResponse);

        response.getWriter().write(jsonResponse);
    }
}
